package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator"
	"github.com/satori/go.uuid"
	"net/http"
	"unicode/utf8"
)

var validate *validator.Validate

func init() {
	validate = validator.New() //初始化
}

func checkNameFunc(f validator.FieldLevel) bool {
	count := utf8.RuneCountInString(f.Field().String())
	if count >= 2 && count <= 12 {
		return true
	}
	return false
}

func CheckUserV1(c *gin.Context) {
	type UserData struct {
		Id   string `validate:"uuid" json:"id"`           //UUID 类型
		Name string `validate:"checkName" json:"name"`    //自定义校验,长度2到12
		Age  uint8  `validate:"min=0,max=120" json:"age"` //0<=Age<=120
	}
	validate.RegisterValidation("checkName", checkNameFunc)

	var user UserData
	err := c.Bind(&user)
	if err != nil {
		c.JSON(http.StatusBadRequest, "请求参数错误！")
		return
	}
	//自定义校验
	err = validate.Struct(user)
	if err != nil {
		//输出错误的校验值
		for _, e := range err.(validator.ValidationErrors) {
			fmt.Println("错误的字段：", e.Field())
			fmt.Println("错误的值：", e.Value())
			fmt.Println("错误的tag：", e.Tag())
		}
		c.JSON(http.StatusBadRequest, "数据校验失败")
		return
	}
	c.JSON(http.StatusOK, "成功")
	return
}

func CheckUserV2(c *gin.Context) {
	//更多校验规则： https://github.com/go-playground/validator
	type ValAddress struct {
		Province string `validate:"required" json:"province"`    //非空
		City     string `validate:"required" json:"city"`        //非空
		Phone    string `validate:"numeric,len=11" json:"phone"` //数字类型，长度为11
	}
	type ValUser struct {
		Name    string       `validate:"required" json:"name"`        //非空
		Age     uint8        `validate:"gte=0,lte=130" json:"age"`    //  0<=Age<=130
		Email   string       `validate:"required,email" json:"email"` //非空，email格式
		Address []ValAddress `validate:"dive" json:"address"`         //dive关键字表示进入到嵌套结构体进行判断
	}

	/*
		//生成测试数据
		address := ValAddress{
			Province: "浙江省",
			City:     "杭州市",
			Phone:    "15800001111",
		}
		userDemo := ValUser{
			Name:    "张三",
			Age:     20,
			Email:   "test@163.com",
			Address: []ValAddress{address, address},
		}
		c.JSON(http.StatusOK, userDemo)
		return
	*/

	//参数绑定
	var user ValUser
	err := c.Bind(&user)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误，绑定失败！")
		return
	}
	//执行参数的校验
	err = validate.Struct(user)
	if err != nil {
		//断言为：validator.ValidationErrors，类型为：[]FieldError
		for _, e := range err.(validator.ValidationErrors) {
			fmt.Println("错误的字段：", e.Field())
			fmt.Println("错误的值：", e.Value())
			fmt.Println("错误的tag：", e.Tag())
		}
		c.JSON(http.StatusBadRequest, "数据校验失败！")
		return
	}

	c.JSON(http.StatusOK, "数据校验成功！")
	return
}

// 生成uuid
func CreateUuid(c *gin.Context) {
	fmt.Println("uuid", uuid.NewV4())
}

// @Tags 注册接口
// @Summary 注册
// @Description register
// @Accept json
// @Produce json
// @Param username formData string true "用户名"
// @Param password formData string true "密码"
// @Success 200 {string} json "{"code":200,"msg":"注册成功","data":"OK"}"
// @Router /home/user/register [post]
func Register(c *gin.Context) {
	type User struct {
		UserName string `json:"username"`
		Password string `json:"password"`
	}
	type Response struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
		Data string `json:"data"`
	}

	var user User
	//err := c.Bind(&user)
	err := c.BindQuery(&user)
	if err != nil {
		fmt.Println("绑定错误：", err)
		c.JSON(http.StatusBadRequest, "数据错误！")
		return
	}
	c.JSON(http.StatusOK, Response{
		Code: http.StatusOK,
		Msg:  "注册成功",
		Data: "OK",
	})
}

// @Tags 获取用户信息
// @Summary 获取用户的基本信息
// @Description getUserInfo
// @Accept json
// @Produce json
// @Param id query string true "用户ID"
// @Param name query string false "用户名"
// @Success 200 {string} json "{"code":200,"data":{"id":"100","name":"张三"},"msg":"OK"}"
// @Router /home/user/userinfo [get]
func UserInfo(c *gin.Context) {
	id := c.Query("id")
	name := c.Query("name")
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "OK",
		"data": gin.H{
			"id":   id,
			"name": name,
		},
	})
}
